<?php
    /*

     Version: MPL 1.1

     Software distributed under the License is distributed on an "AS IS"
     basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     License for the specific language governing rights and limitations
     under the License.

     The Original Code is KASSIOP Framework.

     The Initial Developer of the Original Code is SURIAN Nicolas (aka NairuS) <me@nairus.fr>.
     Portions created by the Initial Developer are Copyright (C) 2010
     The Initial Developer. All Rights Reserved.

     Contributor(s):

     Alternatively, the contents of this file may be used under the terms
     of the MPL license Version 1.1 (the  "MPL" License"), in which case the
     provisions of Version: MPL 1.1 License are applicable instead of those
     above.  If you wish to allow use of your version of this file only
     under the terms of the MPL License and not to allow others to use
     your version of this file under the MPL, indicate your decision by
     deleting  the provisions above and replace  them with the notice and
     other provisions required by the MPL License.  If you do not delete
     the provisions above, a recipient may use your version of this file
     under either the MPL License.

     The contents of this file are subject to the Mozilla Public License
     Version 1.1 (the "License"); you may not use this file except in
     compliance with the License. You may obtain a copy of the License at
     http://www.mozilla.org/MPL/

    */


    require_once 'PHPUnit/Framework.php';
    require_once dirname( __FILE__ ) . '/../../../../kassiop/core/Autoload.php' ;
    Autoload::register() ;

    /**
     * The unit test class of the FileValidator class.
     *
     * @package    unittests.kassiop.system
     * @subpackage validators
     *
     * @author NairuS
     * @version 1.2 $Rev: 90 $ $Date: 2011-01-16 09:23:26 +0000 (Sun, 16 Jan 2011) $ $Author: nicolas.surian $
     */
    class FileValidatorTest extends PHPUnit_Framework_TestCase
    {
        /**
         * Defines the bad file path to validate.
         *
         * @var string
         */
        protected $badPath ;

        /**
         * Defines the file path to validate.
         *
         * @var string
         */
        protected $path ;

        /**
         * The saved name wanted.
         *
         * @var string
         */
        protected $savedName;

        /**
         * Defines the file upload path after validation.
         *
         * @var string
         */
        protected $uploadPath ;

        /**
         * Defines the validator to test.
         *
         * @var FileValidator
         */
        protected $validator ;

        protected function setUp()
        {
            Configuration::includeBootstrap() ;
            $this->badPath    = realpath( dirname( __FILE__ ) . '/../data/sample/bad_file' );
            $this->path       = realpath( dirname( __FILE__ ) . '/../data/sample/test.txt' );
            $this->savedName  = 'test-validator.txt';
            $this->uploadPath = realpath( UPLOADS_PATH . 'tests' );
            $this->validator  = new FileValidator( array(
                  FileValidator::$maxSizeKey  => 50
                , FileValidator::$mimeTypeKey => array('text/plain')
                , FileValidator::$pathKey     => $this->uploadPath
            ) ) ;
        }

        protected function tearDown()
        {
            unset( $this->validator ) ;
        }

        public function testPath()
        {
            $this->assertTrue(   $this->path !== false, '1. The path of the file to test must be well setted');
            $this->assertEquals( 'test-validator.txt', $this->savedName, '2. The saved name wanted must be well setted' );
            $this->assertTrue(   $this->uploadPath !== false, '3. The upload path of the file to test must be well setted');
            $this->assertTrue(   $this->badPath !== false, '4. The path of the bad file to test must be well setted');
        }

        public function testStaticProperties()
        {
            $this->assertEquals( 'cant_write'          , FileValidator::$cantWriteKey         , '1. The static property must be well setted' );
            $this->assertEquals( 'extension'           , FileValidator::$extensionKey         , '2. The static property must be well setted' );
            $this->assertEquals( 'max_size'            , FileValidator::$maxSizeKey           , '3. The static property must be well setted' );
            $this->assertEquals( 'mime_categories'     , FileValidator::$mimeCategoriesKey    , '4. The static property must be well setted' );
            $this->assertEquals( 'mime_type_guessers'  , FileValidator::$mimeTypeGuessersKey  , '5. The static property must be well setted' );
            $this->assertEquals( 'mime_types'          , FileValidator::$mimeTypeKey          , '6. The static property must be well setted' );
            $this->assertEquals( 'no_tmp_dir'          , FileValidator::$noTmpDirKey          , '7. The static property must be well setted' );
            $this->assertEquals( 'partial'             , FileValidator::$partialKey           , '8. The static property must be well setted' );
            $this->assertEquals( 'path'                , FileValidator::$pathKey              , '9. The static property must be well setted' );
            $this->assertEquals( 'validated_file_class', FileValidator::$validatedFileClassKey, '10. The static property must be well setted' );
        }

        public function testClean()
        {
            // simulate the $_FILES values.
            $values = array( 'name' => 'test.txt', 'tmp_name' => $this->path, 'type' => 'text/plain' );
            $file   = $this->validator->clean($values);
            $this->assertTrue( $file instanceof ValidatedFile, '1. The FileValidator must return an instance of ValidatedFile');

            try
            {
                $values['error'] = UPLOAD_ERR_CANT_WRITE;
                $file            = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue(   $e instanceof ErrorBaseValidator, '2.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'Failed to write file to disk.', $e->getMessage(), '2.2 The error message must be well formatted' );
            }

            try
            {
                $values['error'] = UPLOAD_ERR_EXTENSION;
                $file            = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '3.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'File upload stopped by extension.', $e->getMessage(), '3.2 The error message must be well formatted' );
            }

            try
            {
                $values['error'] = UPLOAD_ERR_FORM_SIZE;
                $file   = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '4.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'File is too large (maximum is 0 bytes).', $e->getMessage(), '4.2 The error message must be well formatted' );

            }

            try
            {
                $values['error'] = UPLOAD_ERR_INI_SIZE;
                $file            = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '5.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'File is too large (maximum is 32M bytes).', $e->getMessage(), '5.2 The error message must be well formatted' );
            }

            try
            {
                $values['error'] = UPLOAD_ERR_NO_TMP_DIR;
                $file            = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '6.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'Missing a temporary folder.', $e->getMessage(), '6.2 The error message must be well formatted' );
            }

            try
            {
                $values['error'] = UPLOAD_ERR_PARTIAL;
                $file            = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '7.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'The uploaded file was only partially uploaded.', $e->getMessage(), '7.2 The error message must be well formatted' );
            }

            try
            {
                $values['error'] = 9;
                $file            = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof InvalidArgumentException, '8.1 The validator must throw an instance of InvalidArgumentException');
                $this->assertEquals( 'The file upload failed with an unknown error value.', $e->getMessage(), '8.2 The error message must be well formatted' );
            }

            try
            {
                $values['error'] = UPLOAD_ERR_OK;
                $values['size']  = 90;
                $file           = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '9.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'File is too large (maximum is 50 bytes).', $e->getMessage(), '9.2 The error message must be well formatted' );
            }

            try
            {
                unset($values['size']) ;
                $values['tmp_name'] = $this->badPath;
                $file               = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '10.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'Invalid mime type (text/x-shellscript).', $e->getMessage(), '10.2 The error message must be well formatted' );
            }

            try
            {
                unset($values['tmp_name']) ;
                $file = $this->validator->clean($values);
            }
            catch( Exception $e )
            {
                $this->assertTrue( $e instanceof ErrorBaseValidator, '11.1 The validator must throw an instance of ErrorBaseValidator');
                $this->assertEquals( 'Invalid.', $e->getMessage(), '11.2 The error message must be well formatted' );
            }
        }

        public function testGetMessage()
        {
            $this->assertEquals( 'Failed to write file to disk.'                   , $this->validator->getMessage( FileValidator::$cantWriteKey ), '1. The message must be well setted' );
            $this->assertEquals( 'File upload stopped by extension.'               , $this->validator->getMessage( FileValidator::$extensionKey ), '2. The message must be well setted' );
            $this->assertEquals( 'File is too large (maximum is %max_size% bytes).', $this->validator->getMessage( FileValidator::$maxSizeKey )  , '3. The message must be well setted' );
            $this->assertEquals( 'Invalid mime type (%mime_types%).'               , $this->validator->getMessage( FileValidator::$mimeTypeKey ) , '4. The message must be well setted' );
            $this->assertEquals( 'Missing a temporary folder.'                     , $this->validator->getMessage( FileValidator::$noTmpDirKey ) , '5. The message must be well setted' );
            $this->assertEquals( 'The uploaded file was only partially uploaded.'  , $this->validator->getMessage( FileValidator::$partialKey )  , '6. The message must be well setted' );
        }

        public function testGetOption()
        {
            $this->assertEquals( 50, $this->validator->getOption( FileValidator::$maxSizeKey ), '1. The option must be well setted.' );
            $this->assertEquals( array('text/plain'), $this->validator->getOption( FileValidator::$mimeTypeKey ), '2. The option must be well setted.' );
            $this->assertEquals( UPLOADS_PATH . 'tests', $this->validator->getOption( FileValidator::$pathKey ), '3. The option must be well setted.' );
            $this->assertEquals( 'ValidatedFile', $this->validator->getOption( FileValidator::$validatedFileClassKey ), '4. The option must be well setted.' );
            $this->assertEquals(
                array(
                'web_images' => array(
                    'image/jpeg'
                    ,'image/pjpeg'
                    ,'image/png'
                    ,'image/x-png'
                    ,'image/gif'
                    )
                )
                , $this->validator->getOption( FileValidator::$mimeCategoriesKey ), '5. The option must be well setted.' );

            $mimeTypeGuessers = $this->validator->getOption( FileValidator::$mimeTypeGuessersKey );
            $this->assertTrue( is_array( $mimeTypeGuessers ), '5.1 The option must be an array.' );
            $this->assertTrue( count( $mimeTypeGuessers ) == 3, '5.2 The option must be have 3 elements.' );

            $this->assertTrue(   $mimeTypeGuessers[0][0] instanceof FileValidator, '6.1 The firt element must be an instance of FileValidator' );
            $this->assertEquals( 'guessFromFileinfo', $mimeTypeGuessers[0][1], '6.2 The second element must be well setted' );

            $this->assertTrue(   $mimeTypeGuessers[1][0] instanceof FileValidator, '7.1 The firt element must be an instance of FileValidator' );
            $this->assertEquals( 'guessFromMimeContentType', $mimeTypeGuessers[1][1], '7.2 The second element must be well setted' );

            $this->assertTrue(   $mimeTypeGuessers[2][0] instanceof FileValidator, '8.1 The firt element must be an instance of FileValidator' );
            $this->assertEquals( 'guessFromFileBinary', $mimeTypeGuessers[2][1], '8.2 The second element must be well setted' );
        }
    }
?>